﻿using Flee.PublicTypes;
using Sunny.UI;
using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace SmartMotion.Core.Tools
{
    public class ActionExpression : ActionItem
    {
        private IGenericExpression<bool> bGeneric;

        public ActionExpression() : base()
        {
            VarAlias = new List<string>();
        }

        public List<string> VarAlias { get; set; }

        public string BoolExpression { get; set; }

        public override bool Initilize()
        {
            Stopwatch sw = Stopwatch.StartNew();
            //1,创建上下文类
            ExpressionContext context = new ExpressionContext();
            //2,引用类型
            context.Imports.AddType(typeof(Math));
            //3准备变量
            foreach (var guid in VarIDs)
            {
                var varInfo = GlobalVars.Ins.GetVar(guid);
                if (varInfo!=null)  
                {
                    context.Variables[varInfo.Name] = varInfo.Value;
                }
            }

        
            //4,编译
            bGeneric = context.CompileGeneric<bool>(BoolExpression);
            Em.GetEvent<DebugMessage>().Publish($"编译{ItemName}成功 耗时{sw.ElapsedMilliseconds}");
            return true;
        }

        protected override bool RunMethod()
        {
            if (bGeneric==null)
            {
                Initilize();
            }
            //5,执行
            bool result = false;
            try
            {
                 result = bGeneric.Evaluate();
                 Em.GetEvent<DebugMessage>().Publish($"运行表达式{BoolExpression}={result}");

            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Em.GetEvent<DebugMessage>().Publish($"运行表达式{BoolExpression}失败\r {e.Message}");
            }
          

            return result;
        }

        public override UIForm GetConfigForm()
        {
            return new FrmExpression(this);
        }

        public override UIPage GetParmsPage()
        {
            return null;
        }
    }
}